#include "Logging/include/Logging.h"
#include "Utility/include/Utility.h"
#include <fstream>

QMutex  Logging::itsMutex;
QString Logging::itsLogFileName;

void Logging::useLogging()
{
    qInstallMessageHandler(Logging::init);
    QDir dir(LOG_DIR);
    if (!dir.exists())
    {
         QDir dir;
         dir.mkdir(LOG_DIR);
    }

    //创建log文件
    QString currentDate = QDateTime::currentDateTime().toString("yyyy_MM_dd_hh_mm_ss");
    QString logName = "PhoenixLog_" + currentDate + ".txt";
    itsLogFileName = QString(LOG_DIR) + "/" + logName;
}

void Logging::init(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    // 加锁
    itsMutex.lock();

    //信息分类
    QString strMsg("");
    switch(type)
    {
    case QtDebugMsg:
        strMsg = QString("Debug:");
        break;
    case QtInfoMsg:
        strMsg = QString("Info:");
        break;
    case QtWarningMsg:
        strMsg = QString("Warning:");
        break;
    case QtCriticalMsg:
        strMsg = QString("Critical:");
        break;
    case QtFatalMsg:
        strMsg = QString("Fatal:");
        break;

        default:
            break;
    }

    std::string file;
    if(context.file)
    {
        //文件名、函数名、行数
        std::vector<std::string> files;
        Utility::split(files, context.file, '\\');
        file = files.size() > 0 ? files[files.size()-1] : context.file;
    }

    strMsg += QString("Function: %1  File: %2  Line: %3 ").arg(context.function).arg(file.c_str()).arg(context.line);
    // 时间和内容
    QString strDateTime = QDateTime::currentDateTime().toString("hh:mm:ss");
    QString strMessage = QString("%1 %2:%3").arg(strDateTime).arg(strMsg).arg(msg.constData());
    QByteArray localMsg = strMessage.toLocal8Bit();
    std::ofstream ofs;
    ofs.open(itsLogFileName.toStdString(), std::ios::app);
    ofs << localMsg.toStdString() << std::endl;    //利用<<可以向文件中写数据
    std::cout << localMsg.toStdString() << std::endl;

    ofs.close();


    // 解锁
    itsMutex.unlock();
}
